<?php
/*========================================= JooSam =========================================/
/																							/
/	Extention:		JooSam																	/
/	Created by:		ScriptPlanet.eu															/
/	Site:			http://www.scriptplanet.eu												/
/	Email:			support@scriptplanet.eu													/
/	Support:		http://www.scriptplanet.eu/support										/
/	Copyright:		2011 (c) ScriptPlanet.eu												/
/	License:		CC BY-NC-ND 3.0 ~ http://creativecommons.org/licenses/by-nc-nd/3.0/		/
/	File Version:	0001																	/
/																							/
/========================================== JooSam ========================================*/
// Joomla security
defined('_JEXEC') or die;

class jsamSongdata extends jsamMain{

	## Public Function getInfo will be the only function that
	## can be called from outside

	public function getInfo($who, $data){

		## JooSam counter
		if($who == 'count'){
			return $this->getSongs('count');
		}

		## Ajax search
		else if($who == 'ajax'){
			return $this->getSongs('ajax');
		}
		
		## Letter search
		else if($who == 'letter'){
			return $this->getSongs('letter');
		}

		## Song info
		else if($who == 'songinfo'){
			return $this->songinfo($data);
		}

		## Picture
		else if($who == 'picture'){
			return $this->artistImage($data);
		}

		## Request intro
		else if($who == 'introtext'){
			return $this->introtext();
		}

		## Wrong caller
		else{
			return false;
		}
	}

	protected function introtext(){
		$conf = $this->requestconf();
		$data = $conf['frontpagetext'];
		return $data;
	}

	protected function getSongs($caller){
		
		# connection for samdb
		$sdb = new jsamSamdb();

		# Get configs
		$jsamSettings = $this->settings();
		$jsamRequest = $this->requestconf();
		$joomlaConfig = JFactory::getApplication();
		$jsamEvent = $this->events();
		
		# Some vars asign
		$maxRows = JRequest::getVar('limit', $joomlaConfig->getCfg('list_limit'));
		$startRow = JRequest::getVar('limitstart', 0);
		$startRow = $startRow * $maxRows;
		$def_catView = $jsamRequest['defcat'];
		$evt_catView = $jsamRequest['evtcat'];
		$running_evt = $jsamEvent['isdef'];
		$event_Request = $jsamEvent['sprequests'];
		$songView = $jsamRequest['songtyp'];
		
		# Category View
		if($evt_catView == 'Event' and $running_evt != 'true'){
			$catView = $event_Request;
		}
		else{
			$catView = $def_catView;
		}

		# samdb Search string
		if($caller == 'ajax'){
			$string = JRequest::getVar('term');
		}
		else{
			$string = JRequest::getVar('spstring');
		}

		# samdb search
		if($caller == 'ajax'){
			$search = '%'.$string.'%';
		}
		else if($caller == 'count' and $string != 'nolet' or $caller == 'letter' and $string != 'nolet'){
			$search = $string.'%';
		}
		else{
			$search = '%';
		}

		### All Vars We Use In Data ###
		
		$view_category = $catView;		##	none - all - 'xx','xx','xx'
		$view_songtype = $songView;		##	'S','N','?'
		$rowstart = $startRow;			##	Number of the first row
		$rowcount = $maxRows;			##	Numbers of the rows to the view
		$dbsearch = $search;			##	% - letter% - %search%

		#========================
		# Query work
		#========================

		## When show all categories
		if($view_category == 'all'){

			## By Ajax Search
			if($caller == 'ajax'){
				$query = "	SELECT ID, artist, title
							FROM songlist
							WHERE (artist LIKE '".$dbsearch."' OR title LIKE '".$dbsearch."')
								AND songtype IN (".$view_songtype.")
							ORDER BY artist, title ASC
						";
			}

			## By Counter
			else if($caller == 'count'){
				$query = "	SELECT ID, artist, title
							FROM songlist
							WHERE artist LIKE '".$dbsearch."' 
								AND songtype IN (".$view_songtype.")
							ORDER BY title ASC 
						";
			}

			## By Letter button
			else{ 
				$query = "	SELECT ID, artist, title
							FROM songlist
							WHERE artist LIKE '".$dbsearch."'
								AND songtype IN (".$view_songtype.")
							ORDER BY artist, title ASC
							LIMIT $rowstart, $rowcount
						";
			}
		}

		## When no songview is allowed
		else if($view_category == 'none'){
			$query = 'code001';
		}

		## When not all categories are allowed
		else{

			## By Ajax Search
			if($caller == 'ajax'){
				$query = "	SELECT A.ID, A.artist, A.title
							FROM songlist A, categorylist B
							WHERE (A.artist LIKE '".$dbsearch."' OR A.title LIKE '".$dbsearch."')
								AND B.categoryID IN (".$view_category.")
								AND A.ID = B.songID
								AND A.songtype IN (".$view_songtype.")
							ORDER BY A.artist, A.title ASC
						";
			}

			## By Counter
			else if($caller == 'count'){
				$query = "	SELECT A.ID, A.artist, A.title
							FROM songlist A, categorylist B
							WHERE A.artist LIKE '".$dbsearch."'
								AND B.categoryID IN (".$view_category.")
								AND A.ID = B.songID
								AND A.songtype IN (".$view_songtype.")
							ORDER BY A.title ASC
						";
			}

			## By Letter button
			else{
				$query = "	SELECT A.ID, A.artist, A.title
							FROM songlist A, categorylist B
							WHERE A.artist LIKE '".$dbsearch."'
								AND B.categoryID IN (".$view_category.")
								AND A.ID = B.songID
								AND A.songtype IN (".$view_songtype.")
							ORDER BY A.artist, A.title ASC
							LIMIT $rowstart, $rowcount
						";
			}
		}

		#### BUILD MySQLi For Samdb
		if($query != 'code001'){

			# global
			$data = '';
			$row = '';
			
			# By Counter
			if($caller == 'count'){
				if($sql = $sdb->query($query)){
					$row = $sql->num_rows;
					$sdb->close();
					if($row != ''){
						$pages = ceil($row / $rowcount);
						return $pages;
					}
					else{
						return false;
					}
				}
				else{
					return false;
				}
			}

			# By Ajax and Button
			else{
				if($sql = $sdb->query($query)){
					while($row = $sql->fetch_assoc()){
						$data[] = $row;
					} $sql->free();
					$sdb->close();
					if($data != ''){
						return $data;
					}
					else{
						return false;
					}
				}
				else{
					return false;
				}
			}
		}
		else{
			return false;
		}
	}

	protected function songinfo($songid){
		
		# connection for samdb
		$sdb = new jsamSamdb();
		
		$id = JRequest::getVar('spstring');
		$query = "SELECT artist, title, duration, picture FROM songlist WHERE ID = '".$songid."' ";
		
		# Global
		$data = '';

		# DB Work
		if($sql = $sdb->query($query)){
			while ($row = $sql->fetch_assoc()){
				$data = $row;
			} $sql->free();
			$sdb->close();
			if($data != ''){
				return $data;
			}
			else{
				return false;
			}
		}
		else{
			return false;
		}
	}

	protected function artistImage($songid){

		### Info ########################################################################################
		#																								#
		#	joosam has a function to give a image of the artist you are playing now.					#
		#																								#
		#	joosam can get than info by 2 ways.															#
		#																								#
		#	1. Joomla																					#
		#		All images must be uploaded to <joomlaroot>/media/com_joosam/artist/					#
		#																								#
		#		joosam will get the information from the songlist database of SAM						#
		#		he see there under colom 'picture' xxxx.jpg or subfolder/xxxx.jpg						#
		#																								#
		#		joosam will try to open																	#
		#			<joomlaroot>/media/com_joosam/artist/xxxx.jpg										#
		#			<joomlaroot>/media/com_joosam/artist/subfolder/xxxx.jpg								#
		#																								#
		#		When he can open he will show the artist (live module and song info)					#
		#																								#
		#	2. Lastfm																					#
		#		LastFM has a service for users to use a very large database with song/artist info		#
		#																								#
		#		joosam can use this to. The only thing you need to do is create a LastFM ApiKey.		#
		#		They are free. on http://www.last.fm/api												#
		#																								#
		#		joosam will do a request by lastfm and ask the location of the picture.					#
		#				!!! WARNING !!! A SAM UTF8 DATABASE IS A MUST FOR LASTFM.						#
		#																								#
		#		A ApiKey looks like: b25b959554ed76058ac220b7b2e0a026									#
		#			(This is a test apikey from lastfm. don't use it.)									#
		#																								#
		#################################################################################################

		## Get some configs
		$conf = $this->settings();
		$song = $this->songinfo($songid);

		## Global vars
		$imgwidth = $conf['imgwidth'].'px';
		$imgheight = $conf['imgheight'].'px';
		$source = $conf['imgtype'];
		$result = '';
		
		## Image height/width check
		if($imgheight == 'px' or $imgheight == ''){
			$imgheight = '50px';
		}
		if($imgwidth == 'px' or $imgwidth == ''){
			$imgwidth = '50px';
		}
		
		## LastFM
		if($source == 0){

			## Get Data
			$ApiKey = $conf['imglastfmkey'];
			$Artist = utf8_encode($song['artist']);

			if($ApiKey == ''){
				$result = 'code100';			## No Apikey is given
			}
			else if($Artist == ''){
				$result = 'code101';			## No Artist is given
			}
			else{
				## We have a apikey and artist is given
				$lastfm = array(
							'url' => 'http://ws.audioscrobbler.com/2.0/',
							'method' => 'artist.getinfo',
							'data' => 'artist='.urlencode($Artist),
							'ApiKey' => $ApiKey );
				
				$url = $lastfm['url'].'?method='.$lastfm['method'].'&'.$lastfm['data'].'&api_key='.$lastfm['ApiKey'];
				
				## Check is curl is installed (needed for lastfm
				if(function_exists('curl_init')){
					$srv = curl_init($url);
					curl_setopt($srv, CURLOPT_HEADER, false);
					curl_setopt($srv, CURLOPT_RETURNTRANSFER, true);
					$srvData = curl_exec($srv);
					curl_close($srv);
					if($srvData == ''){
						$result = 'code102';	## Error while connecting to last.fm
					}
					else{
						$lastferrorcd = array();
						preg_match('/\d\d\d/', $srvData, $lastferrorcd);
						$lastferrorcd[] = 'placeholder'; ## placeholde so array 0 always exist
						## Check if lastgm page exist
						if($lastferrorcd[0] == 404){
							$result = 'code103';		## LastFM Error 404 was returned.
						}
						else{
							$xml = simplexml_load_string($srvData);
							$status = $xml->attributes()->status;

							## Lastfm returned artist data
							if($status == 'ok'){
								$image = $xml->artist[0]->image[4];
								if($image == ''){$image = $xml->artist[0]->image[3];}
								if($image == ''){$image = $xml->artist[0]->image[2];}
								if($image == ''){$image = $xml->artist[0]->image[1];}
								if($image == ''){$image = 'code104';}					## LastFM has no image for this artist

								if($image == 'code104'){
									$result = 'code104';
								}
								else{
									$result = '<img src="'.$image.'" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;" />';
								}
							}																
							else if($status == 'failed'){									
								$result = 'code107';										
								$extra = '<p class="jsamImgErr" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;">'.$xml->error.'</p>';		
							}																##################################################################################################
							else{															##	LastFM Results																				##
								$result = 'code105';										##																								##
							}																##	code100		-	no apikey in joosam database												##
						}																	##	code101		-	no artist is given															##
					}																		##	code102		-	not possible to connect to lastfm											##
				}																			##	code103		-	lastfm returned 404 (main url exist but suburl is dead)						##
				else{																		##	code104		-	no image by this artist on lastfm											##
					$result = 'code106';													##	code105		-	Lastfm has changed the response codes.										##
				}																			##	code106		-	no php curl support															##
			}																				##	code107		-	$extra = <p class="jsamImgErr">A LastFM Error.</p>							##
		}																					##	<img src="http/~~~~.png" style="height:00px;width:00px;border:none;margin:0;padding:0;" />	##
																							##																								##
		## Joomla Source																	##	Joomla Results																				##
		else if($source == 1){																##																								##
			$image = $song['picture'];														##	code200 	-	No Picture in database by this song											##
																							##	code201		-	Can't find picture															##
			if($image == ''){																##	<img src="http/~~~~.png" style="height:00px;width:00px;border:none;margin:0;padding:0;" />	##
				$result = 'code200';														##																								##
			}																				##	Global results																				##
			else{																			##																								##
				$base = 'media/com_joosam/artist/';											##	code300		-	The joosam settings are broken												##
				$url = $base.$image;														##																								##
				if(file_exists($url)){														##################################################################################################
					$result = '<img src="'.$url.'" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;" />';
				}
				else{
					$result = 'code201';
				}
			}
		}

		## Setting of joosam are broken
		else{
			$result = 'code300';
		}

		##########################################################################################################################################################
		## Output																																				##
		##																																						##
		##	By a error code Lastfm a <p/> will be the output. When you want a guy thats																			##
		##	yelling replace by the $outputs below (ofc only by the one you want) the																			##
		##	<p class="jsamImgErr" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;">~~~~~~</p>	with							##
		##	<img src="http://userserve-ak.last.fm/serve/252/2665333.jpg" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;" />	##
		##																																						##
		##																																						##
		##########################################################################################################################################################

		## Wrong joosam setting.
		if($result == 'code300'){
			$output = '<p class="jsamImgErr" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;">'.JText::_("COM_JOOSAM_COM_REQUEST_IMG_ERROR").'</p>';
		}

		## LastFM - No ApiKey in database.
		else if($result == 'code100'){
			$output = '<p class="jsamImgErr" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;">'.JText::_("COM_JOOSAM_COM_REQUEST_IMG_NO_APIKEY").'</p>';
		}

		## LastFM - No Artist by this song.
		else if($result == 'code101'){
			$output = '<p class="jsamImgErr" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;">'.JText::_("COM_JOOSAM_COM_REQUEST_IMG_NO_ARTIST_LASTFM").'</p>';
		}

		## LastFM - Error while connecting to LastFM
		else if($result == 'code102'){
			$output = '<p class="jsamImgErr" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;">'.JText::_("COM_JOOSAM_COM_REQUEST_IMG_ERROR_CONNECT_LASTFM").'</p>';
		}

		## LastFM - Error by lastfm server (404)
		else if($result == 'code103'){
			$output = '<p class="jsamImgErr" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;">'.JText::_("COM_JOOSAM_COM_REQUEST_IMG_LASTFM_404_BACK").'</p>';
		}

		## LastFM - No image by this artist
		else if($result == 'code104'){
			$output = '<p class="jsamImgErr" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;">'.JText::_("COM_JOOSAM_COM_REQUEST_IMG_LASTFM_NO_IMAGE").'</p>';
		}

		## LastFM - Changed response
		else if($result == 'code105'){
			$output = '<p class="jsamImgErr" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;">'.JText::_("COM_JOOSAM_COM_REQUEST_IMG_LASTFM_STATUS_ERROR").'</p>';
		}
		
		## JooSam - No php curl support
		else if($result == 'code106'){
			$output = '<p class="jsamImgErr" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;">'.JText::_("COM_JOOSAM_COM_REQUEST_IMG_LASTFM_NO_CURL").'</p>';
		}

		## LastFM - Custom error given by lastFM
		else if($result == 'code107'){
			$output = $extra;
		}

		## Joomla - No picture given in sam database
		else if($result == 'code200'){
			$output = '<p class="jsamImgErr" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;">'.JText::_("COM_JOOSAM_COM_REQUEST_IMG_JOOMLA_NO_SAMPICTURE").'</p>';
		}

		## Joomla - joosam can't find picture on server.
		else if($result == 'code201'){
			$output = '<p class="jsamImgErr" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;">'.JText::_("COM_JOOSAM_COM_REQUEST_IMG_JOOMLA_ERROR_URL_LOAD").$url.'</p>';
		}

		## Unknown error
		else if($result == ''){
			$output = '<p class="jsamImgErr" style="height:'.$imgheight.';width:'.$imgwidth.';border:none;margin:0;padding:0;">'.JText::_("COM_JOOSAM_COM_REQUEST_IMG_UNKNOWN_ERROR_JOOSAM").'</p>';
		}

		## Joosam - LastFM/Joomla - Success - we have a picture.
		else{
			$output = $result;
		}

		## The Return.
		return $output;
	}
}